﻿/*
Copyright (c) 2005-2008, CellAO Team

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    * Neither the name of the CellAO Team nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using AO.Core;
using Cell.Core;
using LuaInterface;
using ZoneEngine.Packets;

namespace ZoneEngine.PacketHandlers
{
    /// <summary>
    /// 
    /// </summary>
    class ChatCmd
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="packet"></param>
        /// <param name="client"></param>
        public static void Read(byte[] packet, Client client)
        {
            #region Bytes / Strings / Ints  setup

            PacketReader _reader = new PacketReader(packet);
            Header _header = _reader.PopHeader();
            _reader.PopByte();
            int unknown = _reader.PopInt();
            Identity target = _reader.PopIdentity();
            int cmdLength = _reader.PopInt();
            string fullArgs = _reader.PopString(cmdLength).TrimEnd(char.MinValue);
            string[] cmdArgs = fullArgs.Split(' ');
            _reader.Finish();

            Client m_client;
            string response;
            int statId;

            #endregion

            switch (cmdArgs[0].ToLower())
            {
                #region /set command
                case "set":
                    if (client.Character.stats.GetStat("GMLevel") == 0)
                    {
                        client.SendChatText("You are not authorized to use this command.");
                        break;
                    }

                    if (cmdArgs.Length != 3)
                    {
                        client.SendChatText("Usage: /set &lt;stat&gt; &lt;value&gt;");
                        client.SendChatText("where stat is stat number or name");
                        break;
                    }

                    if (target.Instance == 0)
                    {
                        client.SendChatText("Unable to find target.");
                        break;
                    }

                    statId = StatsList.GetStatId(cmdArgs[1]);
                    int statNewValue = 1234567890;
                    try
                    {
                        statNewValue = int.Parse(cmdArgs[2]);
                    }
                    catch
                    {
                        try
                        {
                            // For values >= 2^31
                            statNewValue = (int)(uint.Parse(cmdArgs[2]));
                        }
                        catch { }
                    }

                    int statOldValue = Packets.Stat.Set(client, statId, statNewValue, target.Type, target.Instance);

                    response = "Character " + target.Instance + ": Stat " + StatsList.GetStatName(statId) + " (" + statId + ") =";

                    response += " New: " + statNewValue;
                    if (statNewValue < 0)
                        response += " (or " + (uint)statNewValue + " unsigned)";

                    response += " Old: " + statOldValue;
                    if (statOldValue < 0)
                        response += " (or " + (uint)statOldValue + " unsigned)";

                    client.SendChatText(response);

                    break;
                #endregion
                #region /get command
                case "get":
                    if (cmdArgs.Length != 2)
                    {
                        client.SendChatText("Usage: /get &lt;stat&gt;");
                        client.SendChatText("where stat is stat number or name");
                        break;
                    }
                    if (target.Type != 50000)
                    {
                        client.SendChatText("Target must be player/monster/NPC");
                        break;
                    }

                    if (Misc.FindClient.FindClientByID((Server)client.Server, target.Instance, out m_client))
                    {
                        statId = StatsList.GetStatId(cmdArgs[1]);
                        int statValue = m_client.Character.stats.GetStat(statId);

                        response = "Character " + m_client.Character.characterName + " (" + m_client.Character.characterId + "): Stat " + StatsList.GetStatName(statId) + " (" + statId + ") = " + statValue;

                        if (statValue < 0)
                            response += " (or " + (uint)statValue + " unsigned)";

                        client.SendChatText(response);
                    }
                    else
                    {
                        client.SendChatText("Unable to find target.");
                    }
                    break;
                #endregion
                #region /command coorddebug
                case "coorddebug":
                    client.SendChatText(client.Character.coord + " " + client.Character.pf);
                    break;
                #endregion
                #region /teleport command
                case "tp":
                case "teleport":
                case "teleportdynel":
                    if (cmdArgs.Length < 3)
                    {
                        /* Msg 110:13065464 = "Invalid length." */
                        client.SendFeedback(110, 13065464);
                        break;
                    }
                    try
                    {
                        AOCoord coord;
                        int PF, i = 1;

                        coord = new AOCoord(float.Parse(cmdArgs[i++]), client.Character.coord.y, float.Parse(cmdArgs[i++]));

                        if ((cmdArgs.Length > i) && (cmdArgs[i].ToLower() == "y"))
                        {
                            i++;
                            coord.y = float.Parse(cmdArgs[i++]);
                        }

                        if ((cmdArgs.Length > i) && (int.TryParse(cmdArgs[i], out PF)))
                        {
                            PF = int.Parse(cmdArgs[i++]);
                        }
                        else
                        {
                            PF = client.Character.pf;
                        }

                        if (cmdArgs[0].ToLower() == "teleportdynel")
                        {
                            if (!Misc.FindClient.FindClientByID((Server)client.Server, target.Instance, out m_client))
                            { Console.WriteLine("Target not found"); break; }

                            if (!Misc.Playfields.ValidPlayfield(PF))
                            { client.SendFeedback(110, 188845972); break; }
                            m_client.Teleport(coord, m_client.Character.heading, PF);
                        }
                        else
                        {
                            if (!Misc.Playfields.ValidPlayfield(PF))
                            { client.SendFeedback(110, 188845972); break; }
                            client.Teleport(coord, client.Character.heading, PF);
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Error: " + e);
                    }
                    break;
                #endregion
                #region /command assist
                case "assist":
                    if (cmdArgs.Length != 2)
                    {
                        client.SendChatText("Usage: /command assist &lt;name&gt;");
                        break;
                    }
                    if (Misc.FindClient.FindClientByName((Server)client.Server, cmdArgs[1], out m_client))
                    {
                        client.Teleport(m_client.Character.coord, m_client.Character.heading, m_client.Character.pf);
                        break;
                    }
                    break;
                #endregion
                #region /command summon
                case "summon":
                    if (cmdArgs.Length != 2)
                    {
                        client.SendChatText("Usage: /command summon &lt;name&gt;");
                        break;
                    }
                    if (Misc.FindClient.FindClientByName((Server)client.Server, cmdArgs[1], out m_client))
                    {
                        m_client.Teleport(client.Character.coord, client.Character.heading, client.Character.pf);
                        break;
                    }
                    break;
                #endregion
                #region /command ghost
                case "ghost":
                    if (cmdArgs.Length != 2)
                    {
                        client.SendChatText("Usage: /command ghost &lt;name&gt;");
                        break;
                    }
                    if (Misc.FindClient.FindClientByName((Server)client.Server, cmdArgs[1], out m_client))
                    {
                        m_client.Server.DisconnectClient(m_client);
                        break;
                    }
                    break;
                #endregion
                #region /command setname
                case "name":
                case "setname":
                    if (cmdArgs.Length < 3)
                    {
                        client.SendChatText("Usage: /command setname &lt;first/last/nick&gt; &lt;newname&gt;");
                        break;
                    }

                    if (target.Type != 50000)
                    {
                        client.SendChatText("Target must be player");
                        break;
                    }

                    string newName = fullArgs.Substring(cmdArgs[0].Length + 1 + cmdArgs[1].Length + 1);

                    if (Misc.FindClient.FindClientByID((Server)client.Server, target.Instance, out m_client))
                    {
                        switch (cmdArgs[1].ToLower())
                        {
                            case "first":
                            case "firstname":
                                if (newName == "\"\"")
                                    newName = "";
                                client.SendChatText(m_client.Character.characterName + "'s first name has been set to " + newName);
                                m_client.Character.characterFirstName = newName;
                                m_client.Character.WriteNames();
                                break;
                            case "last":
                            case "lastname":
                                if (newName == "\"\"")
                                    newName = "";
                                client.SendChatText(m_client.Character.characterName + "'s last name has been set to " + newName);
                                m_client.Character.characterLastName = newName;
                                m_client.Character.WriteNames();
                                break;
                            case "nick":
                            case "nickname":
                                if (cmdArgs.Length != 3)
                                {
                                    client.SendChatText("Usage: /command setname &lt;first/last/nick&gt; &lt;newname&gt;");
                                    break;
                                }
                                client.SendChatText(m_client.Character.characterName + "'s nick name has been set to " + newName);
                                m_client.Character.characterName = newName;
                                m_client.Character.WriteNames();
                                break;
                            default:
                                client.SendChatText("Usage: /command setname &lt;first/last/nick&gt; &lt;newname&gt;");
                                break;
                        }
                        break;
                    }
                    else
                    {
                        client.SendChatText("Unable to find target.");
                    }
                    break;
                #endregion
                #region /command spawn
                case "spawn":
                    if (cmdArgs.Length != 2)
                    {
                        client.SendChatText("Usage: /command spawn &lt;IDgt;");
                        break;
                    }

                    int ID = int.Parse(cmdArgs[1]);
                    NPC.MobType mob = new NPC.MobType();
                    if (mob.NPCInit(ID) == true)
                    {
                        mob.SetPosition(client.Character.coord);
                        mob.pf = client.Character.pf;
                        mob.Level = 1337;
                        mob.BroadcastPF(client);
                    }
                    else
                    {
                        client.SendChatText("Mob ID [" + ID + "] not found in Mob Templates.");
                    }

                    break;
                #endregion

                #region Default...
                default:
                    //we now check it in the Lua command hook.

                    if (Program.Script.CallHook("OnPlayerCommand", client, cmdArgs[0]) == false)
                    {
                        client.SendChatText("Unknown command.");
                    }

                    break;
                #endregion
            }
        }
    }
}
